package io.gitee.wl4837.alatool.core.util;

import io.gitee.wl4837.alatool.core.getter.MethodBaseFieldGetter;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 树结构工具
 * @author wangliang
 */
public class TreeUtil {

    /**
     * 树结构转数组
     * @param list 树数据
     * @param methodBaseFieldGetter 字段获取器
     * @return 数据列表
     * @param <T> 对象
     * @param <R> 值
     */
    public static <T, R> List<T> toList(List<T> list, MethodBaseFieldGetter<T, R> methodBaseFieldGetter) {
        List<T> data = new ArrayList<>();
        for (T item : list) {
            data.add(item);
            try {
                Field field = ClassUtil.getAllDeclaredField(item, methodBaseFieldGetter);
                field.setAccessible(true);
                data.addAll(toList((List<T>) field.get(item), methodBaseFieldGetter));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return data;
    }

}
